<template>
  <div id="container">
    <div class="password-form">
      <p class="title">修改密码</p>
      <el-form label-width="100px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" disabled></el-input>
        </el-form-item>

        <el-form-item label="原密码" prop="oldPassword">
          <el-input type="password" v-model="form.oldPassword" placeholder="请输入原密码"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" v-model="form.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input type="password" v-model="form.confirmPassword" placeholder="请确认新密码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
  import { loginApi,updatePasswordApi } from '../../api/login';
  import { useLoginEmpStore } from '../../stores/loginEmp';

const formRef = ref(null)
const form = ref({
  username: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
}

const router = useRouter()
const route = useRoute()
const loginEmpStore = useLoginEmpStore()

// 页面加载时获取用户名
onMounted(() => {
  // 从本地存储或状态管理中获取用户名
  const loginEmp = loginEmpStore.loginEmp
  if (loginEmp) {
    form.value.username = loginEmp.username || ''
  } else if (route.query.username) {
    // 若通过参数传递用户名（如忘记密码后跳转）
    form.value.username = route.query.username
  }
})

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const result = await updatePasswordApi(form.value)
        if (result.code === 200) {
          ElMessage.success('密码修改成功')
          // 修改密码后退出登录
          ElMessageBox.confirm('密码修改成功，是否重新登录？', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'question'
          }).then(() => {
            loginEmpStore.clearLoginEmp()
            router.push('/login')
          })
        } else {
          ElMessage.error(result.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码失败', error)
        ElMessage.error('操作失败，请稍后再试')
      }
    } else {
      console.log('验证失败')
      return false
    }
  })
}

const cancel = () => {
  router.push('/login')
}
</script>

<style scoped>
#container {
  padding: 10%;
  height: 100vh;
  background-image: url('../../public/loginBG.png');
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.password-form {
  max-width: 500px;
  padding: 40px;
  margin: 0 auto;
  border-radius: 12px;
  backdrop-filter: blur(8px);
  background-color: rgba(255, 255, 255, 0.5);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  border: 2px solid rgba(255, 16, 16, 0.4);
}

.title {
  font-size: 32px;
  font-family: '楷体';
  text-align: center;
  margin-bottom: 35px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .password-form {
    padding: 30px 20px;
    max-width: 90%;
  }
  
  .title {
    font-size: 28px;
  }
}
</style>